import cloud from '@lafjs/cloud'
let dbName = "web-users"
let uid

export default async function (ctx: FunctionContext) {
  //获取用户id

  if (cloud.utils.isString(ctx.user.uid)) {
    uid = ctx.user.uid
  } else {
    uid = ctx.user.uid._id
  }

  let { code } = ctx.body
  //调用并获取access_token
  const response = await cloud.fetch.get('https://api.weixin.qq.com/cgi-bin/token', {
    params: {
      grant_type: 'client_credential',
      appid: "wx9c3827b9e4e2ea96",
      secret: "122cfacb5c3fdab083f0e354b13f8365",
    }
  });
  const { access_token } = response.data;
  let data = access_token

  //获取access_token的接口地址
  let url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${data}`
  const res = await cloud.fetch.post(url, { code })
  const phoneNumber = res.data.phone_info.purePhoneNumber
  return await updateUser(uid, phoneNumber)//更新用户手机号
}

//更新用户信息
let updateUser = async (uid: String, mobile: Number) => {
  let { wx } = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: uid },
  });

  //查看这个手机号有没有被使用过
  let result = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { mobile }
  });

  let userId

  if (result && result._id) {
    userId = result._id
    if (result.hasOwnProperty("wx")) {
      if (result.wx.openid !== wx.openid) {
        return cloud.utils.requestReturn({ code: 500, msg: "手机号已被使用" })
      }
    } else {
      await cloud.nw.db.update({
        dbName,
        whereJson: { mobile },
        dataJson: { wx }
      });
      await cloud.nw.db.del({
        dbName,
        whereJson: { _id: uid }
      });
    }
  } else {
    await cloud.nw.db.update({
      dbName,
      whereJson: { _id: uid },
      dataJson: { mobile, baseInfo: { mobile } }
    });
    userId = uid
  }
  return cloud.utils.requestReturn({ data: cloud.utils.generateToken(userId) })
}
